<?php

namespace app\common\service;

use app\common\model\StudyPlan as StudyPlanModel;
use app\common\model\Topic;
use app\common\model\UserStudy;
use think\facade\Db;

class StudyPlanService
{

    public function getList($page, $pageSize, $where)
    {
        $query = Db::table('study_plan')
            ->alias('s')
            ->join(['topic' => 't'], 't.id = s.src_id')
            ->where($where);
        $count = $query->count();
        $list = $query->order('s.id', 'desc')->page($page, $pageSize)->field('s.id as id,*')->select()->toArray();

        $ids = [];
        foreach ($list as $key => $val) {
            array_push($ids, $val['src_id']);
        }
        $topic = Db::table('topic')->whereIn('id', $ids)->column("*", "id");

        foreach ($list as $key => $val) {
            $list[$key]['topic'] = empty($topic[$val['src_id']]) ? [] : $topic[$val['src_id']];
        }

        return ['total' => $count, 'list' => $list];
    }

    /**
     * 添加到我的学习计划
     * @param $srcId
     * @param $type
     * @param $uid
     * @param $orderId
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function add($srcId, $type, $uid, $orderId = 0)
    {
        if (!self::get($srcId, $type, $uid)) {
            StudyPlanModel::create(['src_id' => $srcId, 'type' => $type, 'uid' => $uid, 'order_id' => $orderId]);
        }
        return true;
    }

    /**
     * 查询是否已添加到我的学习计划
     * @param $srcId
     * @param $type
     * @param $uid
     * @return \think\Model|StudyPlanModel
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function get($srcId, $type, $uid)
    {
        return StudyPlanModel::where(['src_id' => $srcId, 'type' => $type, 'uid' => $uid])->find();
    }

    public static function updateProgress($srcId, $type, $uid)
    {
        if ($plan = self::get($srcId, $type, $uid)) {
            switch ((int)$type) {
                // 专栏
                case StudyPlanModel::TOPIC:
                    $videoIds = Db::table('video_list')
                        ->where(['topic_id' => $srcId])
                        ->field('id')
                        ->select()
                        ->column('id');
                    $videoCount = count($videoIds);
                    if ($videoCount > 0) {
                        $sum = Db::table('user_study')
                            ->where('uid', $uid)
                            ->where('video_id', 'in', implode(',', $videoIds))
                            ->sum('progress');
                        $plan->progress = $sum > 0 ? sprintf('%.2f', $sum / $videoCount) : 0;
                        // 如果进度100%并且未增加完成数时，增加完成数
                        if (100 == $plan->progress && 0 == $plan->complete) {
                            UserService::setExtValueIncr($uid, UserService::TYPE_EXT_TOTAL_STUDY_COMPLETED);
                            $plan->complete = 1;
                        }
                        $plan->save();
                    }
                    break;
            }
        }
    }

    public static function getTrade($uid, $type, $page)
    {
        if (StudyPlanModel::TOPIC == $type) {
            return Db::table('study_plan')
                ->alias('s')
                ->join('topic t', 't.id = s.src_id')
                ->where(['uid' => $uid, 'type' => $type])
                ->where('order_id', '>', 0)
                ->page($page, 10)
                ->field('t.*')
                ->select();
        }
        if (StudyPlanModel::VIDEO == $type) {
            return Db::table('study_plan')
                ->alias('s')
                ->join('video_list v', 'v.id = s.src_id')
                ->where(['uid' => $uid, 'type' => $type])
                ->where('order_id', '>', 0)
                ->page($page, 10)
                ->field('v.*')
                ->select();
        }
        return [];
    }
}
